
#include <stdio.h>
#include "mem_manage.h"
#include <string.h>

typedef unsigned char u_char;
typedef unsigned int u_int;


int main()
{
	int semid;
	void * smptr;
	u_int mailsize = 0;
	u_char * head;
	char * mailsubject = NULL;
	char * mailtext = NULL;

	//open sem
    semid=getSem(M_SEM_NAME,M_SEM_ID,GET);               //共享内存id号
	mem_start=getMem(M_MEM_NAME,M_MEM_ID,TOTAL_LEN,GET); //打开共享内存
	smptr=mem_start;                                     //共享内存链接

	printf("Read for read sub and text\n");

	for(count = 1;;++count)
	{
		printf("the %d mailtext coming\n",count);
		for(;;) //读第一次
        {
            head = (u_char *)malloc(20*sizeof(u_char));
            assert(head!=NULL);
            memset(head,0,20);
            printf("\n----------------READ MailHead---------------\n");
            readsize = my_read(&smptr,head,semid);  //读取首部信息
                                 //循环等待读取首部信息
            if(readsize == READ_FAILED)
            {
#if DEBUG
                printf("read wait~\n");
#endif
                sleep(1);
            }
            else if(readsize == 0)
            {
                printf("read 0 char~\n");
                sleep(1);
            }
            else
            {
                //printf("\n------------------------Begin Read MailHead-------------------------------\n");
                mailsize = strtonum2(head,12,15);
                printf("mailsize is %u\n",mailsize);
                break;
            }
        }
        for(; ;)    //读第二次
        {
            mailtmpsave = NULL;
            mailtmpsave = (char *)malloc((mailsize)*sizeof(char));
            assert(mailtmpsave!=NULL);
            memset(mailtmpsave,0,mailsize);
            readsize = my_read(&smptr,mailtmpsave,semid);   //读取邮件正文信息
            if(readsize == READ_FAILED)
            {
                printf("read mail fail then sleep\n");
                free(mailtmpsave);
                sleep(1);
            }
            else if(readsize == 0)
            {
                printf("read 0 char of mailcontent~\n");
                free(mailtmpsave);
                sleep(1);
            }
            else
            {
            	write_sharemem(mailtmpsave,readsize,mailcount);
            }	

		}
	}


}

u_int strtonum2(u_char * cnum,u_int low,u_int high)
{
	u_int count,num=0;
	for(count=low;count<=high;count++)
	{
		num=(num<<8)|cnum[count];//只能针对字节移位，对首部长度不起作用
	}
	return num;
}